// 主模块，依赖加载
var app= angular.module('app', [
    'ui.router',
    'ngCookies',
    'mainModule',
    'persionModule',
    'managerModule',
    'loginModule',
    'pascalprecht.translate',
    'angularTreeview',
    'angular-sortable-view',
    'ui.tree',
    'services.config',
    'ngAnimate'
]);

// run方法，angular启动后自动执行
app.run([
    '$rootScope',
    '$cookieStore',
    '$stateParams',
    '$location',
    '$translate',
    function ($rootScope, $cookieStore, $stateParams, $location, $translate) {
        init();
        function init() {
            // 兼容IE，console方法
            window.console= window.console || (function () {
                var c= {};
                c.log= c.warn= c.debug= c.info= c.error= c.time= c.dir= c.profile= c.clear= c.exception= c.trace= c.assert= function () {};
                return c;
            })();

            // 全局定时器存放变量
            $rootScope.intervalArr= [];
        };
        $rootScope.changeLang = function (lang) {
            $translate.use(lang);
        };
    }
]);

// 路由配置
app.config([
    '$stateProvider',
    '$urlRouterProvider',
    '$translateProvider',
    '$httpProvider',
    function ($stateProvider, $urlRouterProvider, $translateProvider, $httpProvider) {
        $urlRouterProvider.otherwise('/index');
        $stateProvider.state('index', {     // 首页
            url: '/index',
            views: {
                'header@index': {
                    templateUrl: './client/app/main/header.html'
                },
                '': {
                    templateUrl: './client/app/main/main.html'
                },
                'footer@index': {
                    templateUrl: './client/app/main/footer.html'
                },
                'body@index': {
                    templateUrl: './client/app/main/body.html'
                }
            }
        }).state('index.persion', { // 个人中心主页
            url: '/persion',
            views: {
                'body@index': {
                    templateUrl: './client/components/persionCenter/persionCenter.html'
                }
            }
        }).state('index.manager', {
            url: '/manager',
            views: {
                'body@index': {
                    templateUrl: './client/components/managerCenter/managerCenter.html'
                }
            }
        }).state('login', {
            url: '/login',
            views: {
                '': {
                    templateUrl: './client/components/login/login.html'
                }
            // data: { //限制路由访问数据 暂时mock的角色
                    // authorizedRoles: [USER_ROLES.admin, USER_ROLES.editor]  
                // }
            }
        });
        //国际化配置
        $translateProvider.useStaticFilesLoader({       //加载静态语言文件
            prefix: 'config/i18n/',
            suffix: '.json'
        });
        $translateProvider.preferredLanguage('zh');
        //注册拦截器
        // $httpProvider.interceptors.push(['httpInterceptor', 'sessionInjector', 'AuthService']);
    }
]);

//以下功能尚未完成

//全局拦截器配置
app.factory('httpInterceptor', [ '$q', '$injector',function($q, $injector) {
    var httpInterceptor = {
        'responseError' : function(response) {
            //401（session过期或者没登陆）和404拦截 也可以把自定义错误码放在response.data里解析
            if (response.status == 401) {  
                //记录登录前的页面再跳转 这里$state和ui-router可能有冲突，具体需要和后端联调时去解决
                var rootScope = $injector.get('$rootScope');  
                var state = $injector.get('$rootScope').$state.current.name;  
                rootScope.stateBeforLogin = state;  
                rootScope.$state.go("login");  
                return $q.reject(response);  
            } else if (response.status === 404) {  
                //暂时还没写404页面
                alert("404!");  
                return $q.reject(response);  
            }  
        },
        'response' : function(response) {
            $rootScope.loading = false;     //请求完成，遮罩层关闭
            return response;
        },
        'request' : function(config) {
            $rootScope.loading = true;  //遮罩层打开，用于屏蔽用户操作，前端方面防止重复提交，拟实现进度显示
            return config;
        },
        'requestError' : function(config){
            return $q.reject(config);
        }
    }
    return httpInterceptor;
}]);

//请求时作用户认证
app.factory('sessionInjector', ['SessionService', function(SessionService) {
    var sessionInjector = {
        request: function(config) {
            //登陆后，为所有请求头添加token发送给后台认证
            if (!SessionService.isAnonymus) {
                //config.headers.token = localStorage.token; 
                config.headers['x-session-token'] = SessionService.token;
            }
            return config;
        }
    };
    return sessionInjector;
}]);

//身份认证事件集中定义 
app.constant('AUTH_EVENTS', {
    loginSuccess: 'auth-login-success',
    loginFailed: 'auth-login-failed',
    logoutSuccess: 'auth-logout-success',
    sessionTimeout: 'auth-session-timeout',
    notAuthenticated: 'auth-not-authenticated',
    notAuthorized: 'auth-not-authorized'
});

//唯一单例SessionService, 暂时mock的字段名, 登陆成功保存后台返回的sessionToken  此处的保存仅作为应用内全局使用，真正保存放到localStorage
app.service('SessionService', function () {
    this.create = function (sessionToken, userId, userRole) {
      this.token = sessionToken;
      this.userId = userId;
      this.userRole = userRole;
      this.isAnonymus = false;
    };
    this.destroy = function () {
      this.token = null;
      this.userId = null;
      this.userRole = null;
      this.isAnonymus = true;
    };
    return this;
});

//登录返回操作
app.factory('AuthService', ['$http', 'SessionService', 'configuration', function ($http, SessionService, configuration) {
    var authService = {};
  
    authService.login = function (credentials) {
      return $http
        .post(configuration.host + '/user/login', credentials)
        .then(function (res) {
            SessionService.create(res.data.token, res.data.user.id,res.data.user.role);
            return res.data.user;
        });
    };
  
    authService.isAuthenticated = function () {
      return !!SessionService.userId;
    };
  
    authService.isAuthorized = function (authorizedRoles) {
      if (!angular.isArray(authorizedRoles)) {
        authorizedRoles = [authorizedRoles];
      }
      return (authService.isAuthenticated() && authorizedRoles.indexOf(SessionService.userRole) !== -1);
    };
    return authService;
  }]);

  //监听路由变化 前端阻止无权限访问
  app.run(['$rootScope', '$interval', '$state', 'AUTH_EVENTS', 'AuthService', function ($rootScope, $interval, $state, AUTH_EVENTS, AuthService) {
    $rootScope.$on('$locationChangeStart', function (event, next) {
        // 清除所有的定时器
        if ($rootScope.intervalArr.length != 0){
            angular.forEach($rootScope.intervalArr, function (item, k) {
                $interval.cancel(item);
                $rootScope.intervalArr.splice(k, 1);
            })
        }
      /*var authorizedRoles = next.data.authorizedRoles;
      if (!AuthService.isAuthorized(authorizedRoles)) {
        event.preventDefault();
        //$state.go("login");//跳转到登录界面
        if (AuthService.isAuthenticated()) {
          //未授权
          $rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
        } else {
          //未登录
          $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated);
        }
      }*/
    });
    $rootScope.loading = false;    
  }]);


